package com.future.singleton;

/**
 * 懒汉式
 * 虽然到了按需初始化的目的，但却带来线程不安全的问题
 */
public class LazySingleTon {

    private static LazySingleTon INSTANCE = null;

    private LazySingleTon() {

    }

    /**
     * 不安全
     *
     * @return
     */
    public static LazySingleTon LazySingleTon() {
        if (null == INSTANCE) {
           /* try {
           // 放大
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            INSTANCE = new LazySingleTon();
        }
        return INSTANCE;
    }

    /**
     * 不安全
     *
     * @return
     */
    public static synchronized LazySingleTon LazySingleTon2() {
        if (null == INSTANCE) {
            synchronized (LazySingleTon.class) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                INSTANCE = new LazySingleTon();
            }
        }
        return INSTANCE;
    }

    /**
     * 双端检索（比较完美）
     *
     * @return
     */
    public static synchronized LazySingleTon doubleCheckSingleTon() {
        if (null == INSTANCE) {
            synchronized (LazySingleTon.class) {
                if (null == INSTANCE) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new LazySingleTon();
                }
            }
        }
        return INSTANCE;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(LazySingleTon.doubleCheckSingleTon().hashCode());
            }).start();
        }
    }

}
